<template>
	<view class="order-detail-page">
		<view class="order-status-header" :class="`status-${orderInfo.orderState}`">
			<text class="status-text">{{ getStatusText(orderInfo.orderState) }}</text>
			<text class="status-desc" v-if="orderInfo.orderState === 10">请在预约时间内前往场地核销</text>
		</view>

		<view class="order-info-section">
			<view class="section-title">订单信息</view>
			<view class="info-item">
				<text class="label">订单编号：</text>
				<text class="value">{{ orderInfo.orderNo }}</text>
			</view>
			<view class="info-item">
				<text class="label">下单时间：</text>
				<text class="value">{{ orderInfo.createTime }}</text>
			</view>
			<view class="info-item">
				<text class="label">球桌：</text>
				<text class="value">{{ orderInfo.productName }}</text>
			</view>
			<view class="info-item">
				<text class="label">预约日期：</text>
				<text class="value">{{ orderInfo.date }} {{ orderInfo.week }}</text>
			</view>
			<view class="info-item">
				<text class="label">预约时间：</text>
				<text class="value">{{ orderInfo.timeSlot }}</text>
			</view>
			<view class="info-item">
				<text class="label">时长：</text>
				<text class="value">{{ orderInfo.duration }}小时</text>
			</view>
		</view>

		<view class="payment-info-section">
			<view class="section-title">费用明细</view>
			<view class="info-item">
				<text class="label">单价：</text>
				<text class="value">￥{{ orderInfo.price }}/小时</text>
			</view>
			<view class="info-item">
				<text class="label">时长：</text>
				<text class="value">{{ orderInfo.duration }}小时</text>
			</view>
			<view class="info-item total-row">
				<text class="label">总计：</text>
				<text class="value total-price">￥{{ orderInfo.orderPayPrice }}</text>
			</view>
		</view>

		<!-- 添加时间段选择和二维码展示 -->
		<view class="verification-section" v-if="orderInfo.priceDateTimeRangeVOList?.length > 0">
			<view class="section-title">{{ userInfo.isAdmin ? '核销二维码' : '用户预约时间段' }}</view>
			<!-- 时间段选择器 -->
			<view class="time-slot-selector" v-if="orderInfo.priceDateTimeRangeVOList?.length > 0">
				<scroll-view class="time-slot-scroll" scroll-x>
					<view class="time-slot-list">
						<view v-for="timeSlot in orderInfo.priceDateTimeRangeVOList" :key="timeSlot.id"
							class="time-slot-item" :class="{ active: selectedTimeSlot?.id === timeSlot.id }"
							@click="selectTimeSlot(timeSlot)">
							{{ formatTimeRange(timeSlot.startTime, timeSlot.endTime) }}
							<!-- 显示时间段状态 -->
							<text class="time-slot-status" :class="getStatusClass(timeSlot.state)">
								{{ getStatusText(timeSlot.state) }}
							</text>
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 二维码展示 -->
			<view class="qrcode-container" v-if="userInfo.isAdmin">
				<view class="selected-time-slot" v-if="selectedTimeSlot">
					{{ formatTimeRange(selectedTimeSlot.startTime, selectedTimeSlot.endTime) }}
					<text class="time-slot-status" :class="getStatusClass(selectedTimeSlot.state)">
						{{ getStatusText(selectedTimeSlot.state) }}
					</text>
				</view>
				<image class="qrcode-image" :src="selectedTimeSlot?.verificationQRCode" mode="aspectFit"
					v-if="selectedTimeSlot?.state === 10 && selectedTimeSlot?.verificationQRCode"></image>
				<view v-else class="expired-tip">
					<text class="expired-text">{{ getTipText(selectedTimeSlot?.state) }}</text>
				</view>
				<text class="qrcode-tip"
					v-if="selectedTimeSlot?.state === 10 && selectedTimeSlot?.verificationQRCode">请向工作人员出示此二维码进行核销</text>
			</view>
		</view>

		<view class="order-action-section">
			<view v-if="orderInfo.orderState === 1 && userInfo.isAdmin" class="action-buttons">
				<button class="action-button secondary-button" @click="btncancelOrder">
					取消订单
				</button>
				<button class="action-button primary-button" @click="payOrder">
					去付款
				</button>
			</view>
			<button v-else-if="orderInfo.orderState === 10 && selectedTimeSlot?.state == 10 && userInfo.isAdmin"
				class="action-button secondary-button" @click="applyRefund">
				订单退款
			</button>
		</view>
	</view>
</template>

<script setup>
import {
	ref,
	onUnmounted
} from 'vue';
import {
	onLoad,
} from '@dcloudio/uni-app';
import {
	getOrderDetails,
	getOrderVerificationCode,
	cancelOrder,
	userOrderRefund,
	adminOrderRefund
} from '@/services/order.js';
import {
	formatDateTimeRange
} from '@/utils/date.js';
const userInfo = uni.getStorageSync('userConfig');
// 订单信息
const orderInfo = ref({});

// 选中的时间段
const selectedTimeSlot = ref(null);

// 二维码刷新定时器
const qrRefreshTimer = ref(null);

// 页面加载
onLoad((options) => {
	if (options.orderNo) {
		loadOrderDetail(options.orderNo);
	}
});

// 页面卸载时清除定时器
onUnmounted(() => {
	console.log('页面卸载喽');
	clearQRCodeRefreshTimer();
});

// 加载订单详情
const loadOrderDetail = async (orderNo) => {
	try {
		const res = await getOrderDetails(orderNo);
		if (res.data) {
			const newOrders = res.data;

			// 处理订单的日期和时间信息
			if (newOrders.priceDateTimeRangeVOList) {
				const {
					formattedDate,
					formattedTimeSlot
				} = formatDateTimeRange(newOrders.priceDateTimeRangeVOList);
				newOrders.date = formattedDate.split(' ')[0];
				newOrders.week = formattedDate.split(' ')[1];
				newOrders.timeSlot = formattedTimeSlot;
				newOrders.duration = newOrders.priceDateTimeRangeVOList.length;
				newOrders.price = newOrders.priceDateTimeRangeVOList[0].price;

				// 初始化选中的时间段为第一个待核销的时间段
				if (newOrders.priceDateTimeRangeVOList.length > 0) {
					// 查找第一个待核销的时间段
					const firstValidTimeSlot = newOrders.priceDateTimeRangeVOList.find(slot => slot.state === 10);
					selectedTimeSlot.value = firstValidTimeSlot || newOrders.priceDateTimeRangeVOList[0];
					// 开始刷新二维码
					if (selectedTimeSlot.value.state === 10 && userInfo.isAdmin) {
						startQRCodeRefresh();
					}
				}
			}

			orderInfo.value = newOrders;
		}
	} catch (error) {
		console.error('获取订单详情失败:', error);
		uni.showToast({
			title: '获取订单详情失败',
			icon: 'none'
		});
	}
};

//统一状态文本获取
const getStatusText = (state) => {
	const statusMap = {
		1: '待支付',
		5: '已取消',
		10: '待核销',
		15: '已退款',
		20: '已核销',
		25: '已过期',
	};
	return statusMap[state] || '未知状态';
};

// 支付订单
const payOrder = () => {
	uni.navigateTo({
		url: `/pages/list/payDetail?orderNo=${orderInfo.value.orderNo}`
	})
};

// 申请退款
const applyRefund = () => {
	uni.showModal({
		title: '申请退款',
		content: `确定要申请退款吗？\n退款时间段：${formatTimeRange(selectedTimeSlot.value.startTime, selectedTimeSlot.value.endTime)}`,
		success: async function (res) {
			if (res.confirm) {
				try {
					// 区分管理员和普通用户退款接口
					let result;
					if (!userInfo.isAdmin) {
						// 管理员退款
						result = await adminOrderRefund(selectedTimeSlot.value.id);
					} else {
						// 普通用户退款
						result = await userOrderRefund(selectedTimeSlot.value.id);
					}
					if (result.code == 200) {
						uni.showToast({
							title: '退款申请提交成功，预计1-3个工作日内处理完成!,',
							icon: 'success'
						});
						clearQRCodeRefreshTimer()
					} else {
						uni.showToast({
							title: result.message || '退款申请失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('退款申请失败:', error);
					uni.showToast({
						title: '退款申请失败',
						icon: 'none'
					});
				}
			}
		}
	});
};

// 取消订单
const btncancelOrder = () => {
	uni.showModal({
		title: '取消订单',
		content: '确定要取消该订单吗？',
		success: async function (res) {
			if (res.confirm) {
				const data = await cancelOrder(orderInfo.value.orderNo);
				if (data.code === 200) {
					uni.showToast({
						title: '取消成功',
						icon: 'success'
					});
					loadOrderDetail(orderInfo.value.orderNo);
				} else {
					uni.showToast({
						title: '取消失败',
						icon: 'none'
					});
				}
			}
		},
	});
};

// 选择时间段
const selectTimeSlot = (timeSlot) => {
	selectedTimeSlot.value = timeSlot;
	// 选中时间段后刷新该时间段的二维码（仅当状态为待核销时）
	if (timeSlot.state === 10 && userInfo.isAdmin) {
		startQRCodeRefresh()
	} else {
		clearQRCodeRefreshTimer();
	}
};

// 开始刷新二维码
const startQRCodeRefresh = () => {
	// 清除上一次存在的定时器
	clearQRCodeRefreshTimer();
	// 刷新二维码
	refreshQRCode();
	qrRefreshTimer.value = setInterval(() => {
		refreshQRCode();
	}, 10000);
};

// 清除二维码刷新定时器
const clearQRCodeRefreshTimer = () => {
	if (qrRefreshTimer.value) {
		clearInterval(qrRefreshTimer.value);
		qrRefreshTimer.value = null;
	}
};

// 刷新二维码
const refreshQRCode = async () => {

	if (!selectedTimeSlot.value) return;

	try {
		// 调用接口获取当前选中时间段的二维码
		const res = await getOrderVerificationCode(
			selectedTimeSlot.value.id
		);
		if (res.code == 200) {
			selectedTimeSlot.value.verificationQRCode = res.data;
			return;
		} else if (res.code == 500) {
			// 时间段已过期，不显示二维码
			selectedTimeSlot.value.verificationQRCode = '';
			clearQRCodeRefreshTimer()
			uni.showToast({
				title: res.message || '该时间段无法生成二维码',
				icon: 'none'
			});
			// 重新获取详情
			loadOrderDetail(orderInfo.value.orderNo);
			return;
		}

	} catch (error) {
		console.error('获取二维码失败:', error);
		selectedTimeSlot.value.verificationQRCode = '';
	}
};


// 格式化时间范围
const formatTimeRange = (startTime, endTime) => {
	const start = startTime.split(' ')[1].substring(0, 5);
	const end = endTime.split(' ')[1].substring(0, 5);
	return `${start}-${end}`;
};

// 统一提示文本获取
const getTipText = (state) => {
	const tipMap = {
		1: '该时间段订单待支付，请先完成订单支付',
		5: '该时间段订单已取消，无法生成二维码',
		15: '该时间段订单已退款，无法生成二维码',
		20: '该时间段订单已核销，无法生成二维码',
		25: '该时间段已过期，无法生成二维码',
	};
	return tipMap[state] || '该时间段暂时无法生成二维码';
};

// 统一状态样式类获取
const getStatusClass = (state) => {
	const statusClassMap = {
		1: 'status-pending-payment',
		5: 'status-canceled',
		10: 'status-to-redemption',
		15: 'status-refund',
		20: 'status-redemption',
		25: 'status-expired',
	};
	return statusClassMap[state] || '';

};
</script>

<style lang="scss">
.order-detail-page {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding: 0 15px 20px;
}

.order-status-header {
	text-align: center;
	padding: 30px 0;
	margin-bottom: 15px;
	border-radius: 8px;
	position: relative;
	overflow: hidden;

	&::before {
		content: "";
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(255, 255, 255, 0.15);
		z-index: 1;
	}

	&.status-1 {
		/* 待支付 */
		background: linear-gradient(135deg, #ff9900, #ffcc00);
	}

	&.status-5 {
		/* 已取消 */
		background: linear-gradient(135deg, #999999, #cccccc);
	}

	&.status-10 {
		/* 待核销 */
		background: linear-gradient(135deg, #165dff, #3399ff);
	}

	&.status-15 {
		/* 已退款 */
		background: linear-gradient(135deg, #999999, #cccccc);
	}

	&.status-20 {
		/* 已核销 */
		background: linear-gradient(135deg, #00cc66, #00ff99);
	}

	&.status-25 {
		/* 已过期 */
		background: linear-gradient(135deg, #999999, #cccccc);
	}

	.status-text {
		font-size: 22px;
		font-weight: bold;
		color: #fff;
		position: relative;
		z-index: 2;
		text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
	}

	.status-desc {
		font-size: 14px;
		color: rgba(255, 255, 255, 0.9);
		position: relative;
		z-index: 2;
		margin-top: 8px;
		display: block;
	}
}

.section-title {
	font-size: 16px;
	font-weight: bold;
	color: #333;
	margin-bottom: 15px;
	padding-bottom: 5px;
	border-bottom: 1px solid #e0e0e0;
}

.order-info-section,
.payment-info-section,
.verification-section {
	background-color: #fff;
	border-radius: 8px;
	padding: 15px;
	margin-bottom: 15px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.info-item {
	display: flex;
	margin-bottom: 12px;

	&.total-row {
		margin-top: 10px;
		padding-top: 10px;
		border-top: 1px dashed #f0f0f0;
	}

	.label {
		flex: 1;
		font-size: 14px;
		color: #666;
	}

	.value {
		flex: 2;
		font-size: 14px;
		color: #333;
		text-align: right;

		&.total-price {
			color: #ff6600;
			font-size: 16px;
			font-weight: bold;
		}
	}
}

.time-slot-selector {
	margin-bottom: 20px;

	.time-slot-scroll {
		white-space: nowrap;
		width: 100%;

		.time-slot-list {
			display: inline-block;
			min-width: 100%;
			padding: 8rpx 0;

			.time-slot-item {
				display: inline-block;
				padding: 8px 15px;
				margin-right: 10px;
				background-color: #f5f5f5;
				border-radius: 20px;
				font-size: 14px;
				color: #666;
				cursor: pointer;
				position: relative;

				&.active {
					background-color: #165dff;
					color: #fff;

					.time-slot-status.status-to-redemption {
						color: #fff;
						background-color: rgba(255, 255, 255, 0.2);
					}

					.time-slot-status.status-redemption {
						color: #fff;
						background-color: rgba(255, 255, 255, 0.2);
					}

					.time-slot-status.status-expired {
						color: #fff;
						background-color: rgba(255, 255, 255, 0.2);
					}

					.time-slot-status.status-canceled {
						color: #fff;
						background-color: rgba(255, 255, 255, 0.2);
					}

					.time-slot-status.status-refund {
						color: #fff;
						background-color: rgba(255, 255, 255, 0.2);
					}
					.time-slot-status.status-pending-payment {
						color: #fff;
						background-color: rgba(255, 255, 255, 0.2);
					}
				}

				.time-slot-status {
					font-size: 12px;
					margin-left: 5px;
					padding: 2px 6px;
					border-radius: 10px;

					&.status-to-redemption {
						color: #165dff;
						background-color: rgba(22, 93, 255, 0.1);
					}

					&.status-redemption {
						color: #00cc66;
						background-color: rgba(0, 204, 102, 0.1);
					}

					&.status-expired {
						color: #999999;
						background-color: rgba(153, 153, 153, 0.1);
					}

					&.status-canceled {
						color: #999999;
						background-color: rgba(153, 153, 153, 0.1);
					}

					&.status-refund {
						color: #999999;
						background-color: rgba(153, 153, 153, 0.1);
					}

					&.status-pending-payment {
						color: #ff9900;
						background-color: rgba(255, 153, 0, 0.1);
					}
				}
			}
		}
	}
}

.qrcode-container {
	text-align: center;

	.selected-time-slot {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		margin-bottom: 15px;

		.time-slot-status {
			font-size: 12px;
			margin-left: 5px;
			padding: 2px 6px;
			border-radius: 10px;

			&.status-to-redemption {
				color: #165dff;
				background-color: rgba(22, 93, 255, 0.1);
			}

			&.status-redemption {
				color: #00cc66;
				background-color: rgba(0, 204, 102, 0.1);
			}

			&.status-expired {
				color: #999999;
				background-color: rgba(153, 153, 153, 0.1);
			}

			&.status-canceled {
				color: #999999;
				background-color: rgba(153, 153, 153, 0.1);
			}

			&.status-refund {
				color: #999999;
				background-color: rgba(153, 153, 153, 0.1);
			}
			&.status-pending-payment {
				color: #ff9900;
				background-color: rgba(255, 153, 0, 0.1);
			}
		}
	}

	.qrcode-image {
		width: 200px;
		height: 200px;
		margin: 0 auto 15px;
	}

	.expired-tip {
		font-size: 14px;
		color: #999;
		display: block;
		margin-bottom: 15px;

		.expired-text {
			font-weight: bold;
		}
	}

	.qrcode-tip {
		font-size: 14px;
		color: #999;
		display: block;
	}
}

.order-action-section {
	padding: 15px 0;

	.action-buttons {
		display: flex;
		gap: 10px;

		.action-button {
			flex: 1;
		}
	}

	.action-button {
		width: 100%;
		padding: 12px 0;
		font-size: 16px;
		border-radius: 6px;
		border: none;

		&.primary-button {
			background-color: #165dff;
			color: #fff;
		}

		&.secondary-button {
			background-color: #fff;
			color: #165dff;
			border: 1px solid #165dff;
		}

		&.disabled-button {
			background-color: #f5f5f5;
			color: #999;
		}
	}
}
</style>